<?php

namespace App\Http\Controllers\Api;

use App\Models\About;
use App\Models\Announcement;
use App\Models\AuctionLog;
use App\Models\Banner;
use App\Models\Goods;
use App\Models\GoodsDetail;
use App\Models\GoodsFile;
use App\Models\GoodsNum;
use App\Models\Message;
use App\Models\Order;
use App\Models\Problems;
use App\Models\Type;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class LobbyController extends Controller
{


    /**
     *统计数据
     * @return \Illuminate\Http\JsonResponse
     */
    public function index()
    {

        $data['all_price'] = Order::sum('price');
        $data['user_count'] = User::count();

        return $this->success($data);
    }

    /**
     * 轮播图
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function banner(Request $request)
    {

        $data = Banner::get();

        return $this->success($data);
    }


    /**
     * 产品分类列表
     * @return \Illuminate\Http\JsonResponse
     */

    public function typeList()
    {
        $data = Type::get(['id', 'title']);

        return $this->success($data);
    }

    /**
     * 推荐商品
     */
    public function recommendGoods()
    {
        $list = Goods::recommend();

        return $this->success($list);
    }

    /**
     * 全部商品
     */
    public function allGoods()
    {
        $data = Goods::where('status', 2)->where('auction_status','>',0)->paginate();

        return $this->success($data);
    }


    /**
     * 产品详情
     * @param Request $request
     */
    public function goodsDetail(Request $request)
    {
        //验证用户输入
        $params = $request->only(['goods_id']);
        $validator = \Validator::make($params, [
            'goods_id' => 'required|exists:goods,id',
        ], [
            'goods_id.*' => '参数错误',
        ]);
        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }

        //产品信息拍卖纪录
        $data['goods'] = Goods::with([
            'image',
            'file',
            'auctions'
        ])->find($request->goods_id);

        $data['detail'] = GoodsDetail::where('goods_id', $request->goods_id)->first();
        $data['count'] = AuctionLog::where('goods_id', $request->goods_id)->count();
        return $this->success($data);
    }


    /***
     *公司信息
     * @return \Illuminate\Http\JsonResponse
     */
    public function about()
    {
        $about = About::find(1);

        return $this->success($about);
    }


    /**
     * 浏览次数
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function browseNum(Request $request)
    {

        //验证用户输入
        $params = $request->only(['goods_id']);
        $validator = \Validator::make($params, [
            'goods_id' => 'required|exists:goods,id',
        ], [
            'goods_id.*' => '参数错误',
        ]);
        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }
        $ip = $request->getClientIp();
        $re = GoodsNum::where(['goods_id' => $request->goods_id, 'ip' => $ip])->first();
        if (!$re) {

            GoodsNum::create([
                'goods_id' => $request->goods_id,
                'ip' => $ip,
                'created_at' => date('Y-m-d  H:i:s')
            ]);
            Goods::where('id', $request->goods_id)->increment('browse');
        }
        return $this->success(['msg' => '添加成功']);

    }


    /**
     * 常见问题
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function problems(Request $request)
    {

        $data = Problems::paginate();

        return $this->success($data);
    }

    /**
     * 常见问题
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function problemsDetail(Request $request)
    {
        $params = $request->only(['problem_id']);
        $validator = \Validator::make($params, [
            'problem_id' => 'required|exists:problems,id',
        ], [
            'goods_id.*' => '参数错误',
        ]);
        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }

        $re = Problems::find($request->problem_id);

        return $this->success($re);
    }

    /**
     * 用户建议
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function message(Request $request)
    {
        $params = $request->only(['message', 'phone', 'url']);
        $validator = \Validator::make($params, [
            'message' => 'required',
            'phone' => 'required|regex:/^1[345789]\d{9}$/|size:11',
        ], [
            'message.required' => '参数错误',
            'phone.*' => '电话号码错误',
        ]);
        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }
        //是否上传图片
        $url = '';
        if (count($request->url) > 0) {
            $url = json_encode($request->url);

        }
        $data = [
            'user_id' => \Auth::id(),
            'message' => $request->message,
            'url' => $url
        ];
        $re = Message::add($data);
        if ($re) {
            return $this->success(['msg' => '成功']);
        }
        return $this->error('失败');
    }


    /**
     *注册协议
     */
    public function announcement()
    {
        $re = Announcement::where('tag', 'registered')->first();

        return $this->success($re);

    }

    /**
     * 全部记录
     * @param Request $request
     */
    public function auctionsLog(Request $request)
    {
        $data = AuctionLog::where('goods_id',$request->goods_id)->select('auction_logs.id', 'auction_logs.goods_id', 'auction_logs.user_id', 'auction_logs.price', 'auction_logs.created_at', 'users.phone')
            ->join('users', 'users.id', '=', 'auction_logs.user_id')
            ->orderBy('auction_logs.id','desc')
            ->paginate();
        foreach ($data as  &$datum){
            $datum->phone =  $str = substr_replace($datum->phone,'****',3,4);
        }
        return $this->success($data);
    }
//    public  function save_phone($phone){
//        $IsWhat = preg_match('/(0[0-9]{2,3}[\-]?[2-9][0-9]{6,7}[\-]?[0-9]?)/i',$phone); //固定电话
//        if($IsWhat == 1){
//            return preg_replace('/(0[0-9]{2,3}[\-]?[2-9])[0-9]{3,4}([0-9]{3}[\-]?[0-9]?)/i','$1****$2',$phone);
//        }else{
//            return  preg_replace('/(1[358]{1}[0-9])[0-9]{4}([0-9]{4})/i','$1****$2',$phone);
//        }
//    }
    public function workMan(Request $request)
    {



        $user = User::find($request->user_id);
        if(!$user){
            return $this->error('错误操作');
        }
        if($user->is_buyers !=  1){
            return $this->error('请先认证买家');
        }

        $user_id = $user->id;
        $goods_id = $request->goods_id;
        $price = $request->price;

        $params = $request->only(['goods_id','price','user_id','client_id']);
        $validator = \Validator::make($params, [
            'goods_id' => 'required|exists:goods,id',
            'price' => 'required',
//            'client_id' => 'required',
            'user_id' => 'required',
        ], [
            'goods_id.*' => '产品参数错误',
            'price.*' => '金额不能为空',
//            'client_id.*' => '金额不能为空',
            'user_id.*' => '金额不能为空',
        ]);
        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }
        try {
            \DB::beginTransaction();
            //查询当前最高价
            $auticon = AuctionLog::where('goods_id', $goods_id)->select('id', 'user_id', 'goods_id', 'price')->orderBy('price', 'desc')->first();
            if ($auticon) {
                //获取当前商品的规则
                $goods = Goods::find($goods_id);
                //获取加价幅度
                //当前最低价
//            dd($auticon->toArray());
//                if ($auticon->user_id == $user_id && $auticon->price  == $price ) {
//                    throw  new  \Exception('已是当前最高价');
//                }
                //查询加价幅度
                $lowest_price = bcadd($auticon->price, $goods->scope_price, 2);
                if ($lowest_price > $price || $auticon->price >= $price) {

                    throw  new  \Exception( $lowest_price);
                }
            }
            $goods = Goods::find($goods_id);
           $re =  AuctionLog::create([
                'user_id' => $user_id,
                'goods_id' => $goods_id,
                'price' => $price
            ]);

            \DB::commit();
            return $this->success(['phone'=>$user->phone,'price'=>$re->price,'created_at'=>date('Y-m-d H:i:s'),'status'=>1,'goods_id'=>$goods_id,'name'=>$goods->title]);
        } catch (\Exception $exception) {

            \DB::rollBack();
            return $this->error($exception->getMessage());
        }



    }
}
